"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Search, Plus, Edit, Trash2 } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Textarea } from "@/components/ui/textarea";

interface Notice {
  noticeId: number;
  accountNum: string;
  releaseTime: string;
  content: string;
}

export default function NoticesPage() {
  const [notices, setNotices] = useState<Notice[]>([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [noticeToDelete, setNoticeToDelete] = useState<number | null>(null);
  const [newNotice, setNewNotice] = useState({
    accountNum: "",
    content: "",
  });
  const [editNotice, setEditNotice] = useState<Notice | null>(null);

  useEffect(() => {
    fetchNotices();
  }, []);

  const fetchNotices = async () => {
    try {
      setIsLoading(true);
      const response = await fetch("/api/notices");

      if (!response.ok) {
        throw new Error("获取公告数据失败");
      }

      const data = await response.json();
      setNotices(data.notices);
    } catch (error) {
      console.error("获取公告数据失败:", error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleCreateNotice = async () => {
    try {
      if (!newNotice.accountNum || !newNotice.content) {
        alert("账号和公告内容不能为空");
        return;
      }

      const response = await fetch("/api/notices", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(newNotice),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "创建公告失败");
      }

      // 重置表单并关闭对话框
      setNewNotice({
        accountNum: "",
        content: "",
      });
      setIsDialogOpen(false);

      // 重新获取公告列表
      fetchNotices();
    } catch (error) {
      console.error("创建公告失败:", error);
      alert(error instanceof Error ? error.message : "创建公告失败");
    }
  };

  const handleEditNotice = (notice: Notice) => {
    setEditNotice(notice);
    setIsEditDialogOpen(true);
  };

  const handleUpdateNotice = async () => {
    if (!editNotice) return;

    try {
      if (!editNotice.content) {
        alert("公告内容不能为空");
        return;
      }

      const response = await fetch("/api/notices", {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          noticeId: editNotice.noticeId,
          content: editNotice.content,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "更新公告失败");
      }

      // 关闭对话框并重新获取公告列表
      setIsEditDialogOpen(false);
      setEditNotice(null);
      fetchNotices();
    } catch (error) {
      console.error("更新公告失败:", error);
      alert(error instanceof Error ? error.message : "更新公告失败");
    }
  };

  const handleDeleteNotice = async (noticeId: number) => {
    setNoticeToDelete(noticeId);
    setIsDeleteDialogOpen(true);
  };

  const confirmDeleteNotice = async () => {
    if (!noticeToDelete) return;

    try {
      const response = await fetch(`/api/notices?id=${noticeToDelete}`, {
        method: "DELETE",
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "删除公告失败");
      }

      // 关闭对话框并重新获取公告列表
      setIsDeleteDialogOpen(false);
      setNoticeToDelete(null);
      fetchNotices();
    } catch (error) {
      console.error("删除公告失败:", error);
      alert(error instanceof Error ? error.message : "删除公告失败");
    }
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
      second: "2-digit",
    });
  };

  // 过滤公告
  const filteredNotices = notices.filter(
    (notice) =>
      notice.content.toLowerCase().includes(searchTerm.toLowerCase()) ||
      notice.accountNum.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight">公告管理</h1>
        <p className="text-muted-foreground">查看和管理系统公告信息</p>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
          <CardTitle className="text-xl font-bold">公告列表</CardTitle>
          <div className="flex items-center space-x-2">
            <div className="relative">
              <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
              <Input
                type="search"
                placeholder="搜索公告..."
                className="pl-8 w-[250px]"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
              <DialogTrigger asChild>
                <Button>
                  <Plus className="mr-2 h-4 w-4" />
                  添加公告
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>添加新公告</DialogTitle>
                  <DialogDescription>
                    请填写以下信息创建新的公告
                  </DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="accountNum" className="text-right">
                      发布账号
                    </Label>
                    <Input
                      id="accountNum"
                      value={newNotice.accountNum}
                      onChange={(e) =>
                        setNewNotice({
                          ...newNotice,
                          accountNum: e.target.value,
                        })
                      }
                      className="col-span-3"
                      required
                    />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="content" className="text-right">
                      公告内容
                    </Label>
                    <Textarea
                      id="content"
                      value={newNotice.content}
                      onChange={(e) =>
                        setNewNotice({ ...newNotice, content: e.target.value })
                      }
                      className="col-span-3"
                      rows={5}
                      required
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button
                    variant="outline"
                    onClick={() => setIsDialogOpen(false)}
                  >
                    取消
                  </Button>
                  <Button onClick={handleCreateNotice}>创建</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </CardHeader>
        <CardContent>
          {isLoading ? (
            <div className="flex justify-center items-center h-[400px]">
              <p>加载中...</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>发布账号</TableHead>
                  <TableHead>发布时间</TableHead>
                  <TableHead>公告内容</TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredNotices.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} className="text-center h-24">
                      未找到匹配的公告
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredNotices.map((notice) => (
                    <TableRow key={notice.noticeId}>
                      <TableCell>{notice.noticeId}</TableCell>
                      <TableCell>{notice.accountNum}</TableCell>
                      <TableCell>{formatDate(notice.releaseTime)}</TableCell>
                      <TableCell className="max-w-md truncate">
                        {notice.content}
                      </TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleEditNotice(notice)}
                        >
                          <Edit className="h-4 w-4" />
                        </Button>
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleDeleteNotice(notice.noticeId)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

      {/* 编辑公告对话框 */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>编辑公告</DialogTitle>
            <DialogDescription>修改公告内容</DialogDescription>
          </DialogHeader>
          {editNotice && (
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-accountNum" className="text-right">
                  发布账号
                </Label>
                <Input
                  id="edit-accountNum"
                  value={editNotice.accountNum}
                  className="col-span-3"
                  disabled
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="edit-content" className="text-right">
                  公告内容
                </Label>
                <Textarea
                  id="edit-content"
                  value={editNotice.content}
                  onChange={(e) =>
                    setEditNotice({ ...editNotice, content: e.target.value })
                  }
                  className="col-span-3"
                  rows={5}
                  required
                />
              </div>
            </div>
          )}
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsEditDialogOpen(false)}
            >
              取消
            </Button>
            <Button onClick={handleUpdateNotice}>更新</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除确认对话框 */}
      <AlertDialog
        open={isDeleteDialogOpen}
        onOpenChange={setIsDeleteDialogOpen}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              您确定要删除这个公告吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel onClick={() => setNoticeToDelete(null)}>
              取消
            </AlertDialogCancel>
            <AlertDialogAction onClick={confirmDeleteNotice}>
              确认删除
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
